<template>
  <div class="data-form major-form" v-loading.fullscreen.lock="loading">
    <el-form label-width="auto" size="medium">
      <el-form-item label="类型名称">
        <el-input v-model="majorForm.majorName" class="form-input">
        </el-input>
      </el-form-item>
    </el-form>
    <div style="text-align:center">
      <el-button size="medium" type="primary" @click="saveMajor">
        <span v-if="type==='add'">新增</span>
        <span v-else>修改</span>
      </el-button>
    </div>
  </div>
</template>

<script>
  import BranchApi from 'services/branchApi';

  import MajorTypeForm from 'models/branch/majorTypeForm';

  export default {
    props: {
      major: {
        type: Object,
        default () {
          return null;
        }
      },
      type: {
        type: String,
        default: 'add'
      }
    },

    data() {
      let majorForm;
      if (this.type === 'add') {
        majorForm = new MajorTypeForm();
      } else {
        majorForm = _.cloneDeep(this.major);
      }
      return {
        loading: false,
        majorForm
      };
    },

    methods: {
      saveMajor() {
        let majorForm = this.majorForm;
        let code = majorForm.checkValid();
        if (code !== '') {
          let msg = this.i18n.getMsg(`branch.error.major.${code}`);
          this.$message(msg);
          return;
        }

        if (this.type === 'add') {
          this.addMajor(majorForm);
        } else {
          this.updateMajor(majorForm);
        }
      },

      addMajor(majorForm) {
        this.loading = true;
        BranchApi.addMajor(majorForm).then(() => {
          this.loading = false;
          this.$alert('主营类型新增成功', '信息', {
            callback: () => {
              this.$emit('save-success');
            }
          });
        }).catch(() => {
          this.loading = false;
        });
      },

      updateMajor(majorForm) {
        this.loading = true;
        BranchApi.updateMajor(majorForm).then(() => {
          this.loading = false;
          this.$alert('主营类型修改成功', '信息', {
            callback: () => {
              this.$emit('save-success');
            }
          });
        }).catch(() => {
          this.loading = false;
        });
      }
    }
  };

</script>

<style lang="scss" scoped>
  @import '~viewStyle/dataForm';

</style>
